package com.mylogistics.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.mylogistics.mapper.UserMapper;
import com.mylogistics.pojo.User;
import com.mylogistics.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    //注册账号
    public void register(String username, String password) {
        User user = new User();
        user.setUsername(username);
        String encode = new BCryptPasswordEncoder().encode(password);
        user.setPassword(encode);
        user.setRole("user");
        userMapper.insert(user);
    }

    @Override
    //根据用户名查找用户
    @Cacheable(value = "cacheTest",key = "#username")
    public User getUserByUsername(String username) {
        System.out.println("操作数据库");
        return userMapper.selectOne(new QueryWrapper<User>().eq("username",username));
    }

    @Override
    //根据用户名删除用户
    @CacheEvict(value = "cacheTest",key= "#username")
    public void delUser(String username) {
        System.out.println("删除数据库");
        userMapper.delete(new QueryWrapper<User>().eq("username",username));
    }

    @Override
    //更新用户数据
    @CachePut(value = "cacheTest",key= "#user.username")
    public User edit(User user) {
        System.out.println("更新数据库");
        userMapper.updateById(user);
        return user;
    }

    @Override
    //查找所有用户信息
    public Collection<?> list() {
        return userMapper.selectList(null);
    }
}
